package com.woniuxy.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.woniuxy.domain.Order;
import com.woniuxy.service.IOrderService;
import com.woniuxy.service.IProductService;
import com.woniuxy.service.impl.OrderServiceImpl2;
import com.woniuxy.util.Constants;
import com.woniuxy.util.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author gaopeng
 * @create 2020/04/2020/4/8 10:49:26
 */
@RestController
public class OrderController {
//    @Autowired
//    private DiscoveryClient discoveryClient;

//    @Autowired
//    private RestTemplate restTemplate;



    @Autowired
    private IProductService productService;

    @Autowired
    private IOrderService service;

    @Autowired
    private OrderServiceImpl2 service2;

   // @Autowired
    //private Redisson redisson;

    @PostMapping("/orders/{pid}/{number}")
    public ResultVO create(@PathVariable Integer pid, @PathVariable Integer number) {
       // RLock pid1 = redisson.getLock("pid");
       // pid1.lock();
        try {

            Order order = new Order();
            // 这就是让当前的Order微服务，向另外一个微服务发起http请求的代码
//            ResultVO resultVO = restTemplate.getForObject( "http://product-service/products/" + pid, ResultVO.class);
            ResultVO resultVO = productService.findByPid(pid);

            Map map = (Map) resultVO.getData();
            Integer stock = (Integer) map.get("stock");
            if(stock > 0) {
                // 下单
                order.setPid(pid);
                order.setPname((String) map.get("pname"));
                order.setPrice((Double) map.get("price"));
                order.setNumber(number);
                order.setUid(1);
                order.setUsername("邓紫棋");
                service.create(order);
//                // 减库存
//                // ResultVO resultVO2 = restTemplate.getForObject("http://product-service/products/deductStock/" + pid + "/" + number, ResultVO.class);
//                ResultVO resultVO2 = productService.deductStock(pid, number);
//
//                if(resultVO2.getStatus() == 200 ) {
//                    return new ResultVO(Constants.OPER_SUCCESS, "下单成功", order);
//                } else {
//                    return new ResultVO(Constants.OPER_SUCCESS, "下单失败，目前库存充足，可能是product服务有问题");
//                }
                return new ResultVO(Constants.OPER_FAILURE, "success!");

            } else {
                throw new RuntimeException("下单失败，库存不足");
            }
        } catch (Exception e) {
            return new ResultVO(Constants.OPER_FAILURE, e.getMessage());
        }finally {
       //     pid1.unlock();
        }

    }


    @GetMapping("/orders/testloadbalance")
    public ResultVO testLoadBalance() {
        // 以下url中的product-service，就是nacos注册中心中的服务名
        // 由于restTemplate已经封装了负载均衡的功能， 所以restTemplate天生就能轮询product-service的所有实例
        // 而不需要我们额外再添加负载均衡的逻辑代码了！
        // product-service有3个实例： 8081 8082 8083
        // ResultVO resultVO = restTemplate.getForObject("http://product-service/products/testloadbalance", ResultVO.class);
        ResultVO resultVO = productService.testLoadBalance();
        return resultVO;
    }


    @GetMapping("/orders/message")
    public String message() {
//        int r = new Random().nextInt(2);
//        if(r == 0) {
//            throw new RuntimeException("random exception occur");
//        }
        service2.message();
        return "message: " + System.currentTimeMillis();
    }

    @GetMapping("/orders/message2")
    public String message2() {
        service2.message();
        return "message2: " + System.currentTimeMillis();
    }


    @GetMapping("/orders/message3")
    @SentinelResource("message3") //必须使用这个注解标识,否则热点规则不生效
    public String message3(String name, Integer age) {
        return name + " " + age;
    }


}